const request = require('./request.js').default;

/**
 * 奖励相关 API
 */
const rewardAPI = {
  /**
   * 获取所有可用奖励
   */
  getAllRewards: () => request('/reward/all', 'GET'),

  /**
   * 根据类型获取奖励
   * @param {string} type - 奖励类型
   */
  getRewardsByType: (type) => request(`/reward/type/${type}`, 'GET'),

  /**
   * 根据积分范围获取奖励
   * @param {number} minPoints - 最小积分
   * @param {number} maxPoints - 最大积分
   */
  getRewardsByPointsRange: (minPoints, maxPoints) => request('/reward/points-range', 'GET', null, { minPoints, maxPoints }),

  /**
   * 获取当前用户可兑换的奖励列表
   */
  getAvailableRewards: () => request('/reward/available', 'GET'),

  /**
   * 获取奖励详情
   * @param {number} rewardId - 奖励ID
   */
  getRewardDetail: (rewardId) => request(`/reward/${rewardId}`, 'GET'),

  /**
   * 兑换奖励
   * @param {number} rewardId - 奖励ID
   */
  redeemReward: (rewardId) => request(`/reward/${rewardId}/redeem`, 'POST'),

  /**
   * 获取当前用户积分信息
   */
  getMyPoints: () => request('/reward/points', 'GET'),

  /**
   * 获取指定用户的积分信息
   * @param {number} userId - 用户ID
   */
  getUserPoints: (userId) => request(`/reward/points/${userId}`, 'GET'),


  /**
   * 获取奖励中心页面数据（灵曜页面专用）
   */
  getRewardCenter: () => request('/reward/center', 'GET'),

  /**
   * 获取奖励类型列表
   */
  getRewardTypes: () => request('/reward/all', 'GET').then(res => {
    const types = [...new Set(res.data.map(reward => reward.type))];
    return { code: 200, data: types };
  }),

  /**
   * 获取用户积分排行榜（可选功能）
   * @param {number} limit - 排行榜数量限制
   */
  getPointsRanking: (limit = 10) => {
    // 这个接口可能需要后端实现
    return request('/reward/ranking', 'GET', null, { limit });
  },

  /**
   * 获取用户积分历史记录（可选功能）
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   */
  getPointsHistory: (page = 1, pageSize = 10) => {
    // 这个接口可能需要后端实现
    return request('/reward/points-history', 'GET', null, { page, pageSize });
  },

  /**
   * 获取用户兑换记录（可选功能）
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   */
  getRedeemHistory: (page = 1, pageSize = 10) => {
    // 这个接口可能需要后端实现
    return request('/reward/redeem-history', 'GET', null, { page, pageSize });
  },

  /**
   * 检查用户是否有足够积分兑换指定奖励
   * @param {number} rewardId - 奖励ID
   */
  checkCanRedeem: (rewardId) => request(`/reward/${rewardId}`, 'GET').then(res => {
    const reward = res.data;
    const canRedeem = reward.userCurrentPoints >= reward.pointsCost;
    return {
      code: 200,
      data: {
        canRedeem,
        userPoints: reward.userCurrentPoints,
        requiredPoints: reward.pointsCost,
        shortage: Math.max(0, reward.pointsCost - reward.userCurrentPoints)
      }
    };
  })
};

module.exports = rewardAPI;
